package com.yupi.yuoj.controller;

import cn.hutool.core.io.FileUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.config.QiniuConfig;
import com.yupi.yuoj.constant.FileConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.manager.CosManager;
import com.yupi.yuoj.model.dto.file.UploadFileRequest;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.enums.FileUploadBizEnum;
import com.yupi.yuoj.service.UserService;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private QiniuConfig qiniuConfig;

    @Value("${video.file.path}")
    private String videoFilePath;

    private static final int BYTE_RANGE_LENGTH = 1024 * 1024; // 每次读取的字节块大小，1MB

    // 正则表达式用于解析 Range 头
    private static final Pattern RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-(\\d*)");

    /**
     * 流式播放视频文件
     * 支持 HTTP Range 请求，实现断点续传和时间点跳转
     *
     * @param filename 视频文件名（不含路径）
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @GetMapping("/{filename:.+}") // .+: 匹配所有字符，包括点
    public void streamVideo(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Path videoFileFullPath = Paths.get(videoFilePath, filename);
        File videoFile = videoFileFullPath.toFile();

        if (!videoFile.exists() || !videoFile.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Video file not found: " + filename);
            return;
        }

        long fileLength = Files.size(videoFileFullPath);
        String rangeHeader = request.getHeader("Range");

        // 设置响应头
        response.setContentType(Files.probeContentType(videoFileFullPath)); // 根据文件类型设置MIME Type
        response.setHeader("Accept-Ranges", "bytes"); // 告诉浏览器支持 Range 请求

        if (rangeHeader == null || rangeHeader.isEmpty()) {
            // 如果没有 Range 请求头，则发送整个文件
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Content-Length", String.valueOf(fileLength));
            Files.copy(videoFileFullPath, response.getOutputStream());
        } else {
            // 处理 Range 请求头
            Matcher matcher = RANGE_PATTERN.matcher(rangeHeader);
            if (!matcher.matches()) {
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Invalid Range header");
                return;
            }

            long start = 0;
            long end = fileLength - 1;

            if (matcher.group(1) != null && !matcher.group(1).isEmpty()) {
                start = Long.parseLong(matcher.group(1));
            }
            if (matcher.group(2) != null && !matcher.group(2).isEmpty()) {
                end = Long.parseLong(matcher.group(2));
            }

            // 确保范围有效
            if (start < 0 || end >= fileLength || start > end) {
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Invalid Range");
                return;
            }

            // 计算实际需要发送的字节数
            long contentLength = end - start + 1;

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206 Partial Content
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            response.setHeader("Content-Length", String.valueOf(contentLength));

            // 使用 RandomAccessFile 读取指定范围的字节
            try (RandomAccessFile raf = new RandomAccessFile(videoFile, "r")) {
                raf.seek(start); // 定位到起始字节
                byte[] buffer = new byte[BYTE_RANGE_LENGTH];
                long bytesRemaining = contentLength;

                while (bytesRemaining > 0) {
                    int bytesToRead = (int) Math.min(bytesRemaining, buffer.length);
                    int bytesRead = raf.read(buffer, 0, bytesToRead);
                    if (bytesRead < 0) { // 文件结束或读取失败
                        break;
                    }
                    response.getOutputStream().write(buffer, 0, bytesRead);
                    bytesRemaining -= bytesRead;
                }
                response.getOutputStream().flush();
            }
        }
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
            UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            Configuration configuration = new Configuration(Region.huadong());
            String fileName = file.getName();
            UploadManager uploadManager = new UploadManager(configuration);
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String fileKey = qiniuConfig.getDirectory() + filepath;
            Response response = uploadManager.put(file, fileKey, upToken);

            // 返回可访问地址
            return ResultUtils.success(qiniuConfig.getDomain()+"/"+fileKey);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
